package org.adream.dreamnt;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.ticket.Ticket;
import org.jasig.cas.ticket.TicketGrantingTicket;
import org.jasig.cas.ticket.registry.TicketRegistry;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

@Component("customLogoutController")
@Controller
public class CasCustomLogoutRestfulApi extends AbstractController{
	
	private TicketRegistry ticketRegistry;
	private CentralAuthenticationService centralAuthenticationService;

	@RequestMapping(path = "/logoutApi")
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String uid = ServletRequestUtils.getStringParameter(request, "blackUid", "");
		if(StringUtils.isEmpty(uid)||StringUtils.isEmpty(uid.trim())) {
			logger.debug("参数uid 空");
			return null;
		}
		//还可以加 token 等等验证信息 保证安全
		
		
		uid = uid.trim();
		
		
		DataSource dataSource = getWebApplicationContext().getBean("dataSource",DataSource.class );
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		String sql = "select mts,is_black from acc_user where uid='" + uid +"'";
		SqlRowSet srs = jdbcTemplate.queryForRowSet(sql);
		while(srs.next()){
			Boolean isBlack = srs.getBoolean("is_black");
			 if(!isBlack) {
		        	logger.debug("uid:"+uid+"没有被拉黑");
		        	return null;
		        }
			String mts = srs.getString("mts");
			Long a = 0l;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				a = sdf.parse(mts).getTime();
			} catch (Exception e1) {
				 logger.error("mts转换错误");
				 return null;
			}
			Long now = new Date().getTime();
			if(Math.abs(now-a)>10000){//10秒为妙
				logger.error("操作过期, 超时了");
				return null;
			}	
			try {
				casLogout(uid);
				return null;
			} catch (Exception e) {
				logger.error("uid:"+uid+"踢出失败！！！");
			}
			
		}
		 
		return null;
	}
	
	private void casLogout(String uid) throws Exception{
		Collection<Ticket> tickets = ticketRegistry.getTickets();
		
		System.out.println("tickets数量:"+tickets.size());
		for(Ticket t:tickets) {
			String ticketId = t.getId();
			TicketGrantingTicket st = t.getGrantingTicket();
			if(st==null) continue;
			
			String username = st.getAuthentication().getPrincipal().getId();
			logger.debug("username:"+username);
			if(StringUtils.isEmpty(username) || !uid.equals(username.trim()))
				{
					logger.debug("条件不符");
					continue;
				}
			
			String ticketGrantingTicketId = st.getRoot().getId();
			try {
				//销毁 TGT
				centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketId);
				//删除ST
				ticketRegistry.deleteTicket(ticketId);
				
			} catch (Exception e) {
				logger.error(ticketGrantingTicketId+":踢出失败！！！");
			}
		}
	}

	public TicketRegistry getTicketRegistry() {
		return ticketRegistry;
	}

	public void setTicketRegistry(TicketRegistry ticketRegistry) {
		this.ticketRegistry = ticketRegistry;
	}

	public CentralAuthenticationService getCentralAuthenticationService() {
		return centralAuthenticationService;
	}

	public void setCentralAuthenticationService(CentralAuthenticationService centralAuthenticationService) {
		this.centralAuthenticationService = centralAuthenticationService;
	}
}